﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security;
using System.Security.Principal;
using System.Web.ClientServices;
using System.Web.ClientServices.Providers;
using System.Web.Security;
using System.Threading;
using Microsoft.Practices.EnterpriseLibrary.Security;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;

namespace Sauth
{
    public class AuthenticationHelper
    {
        /// <summary>
        /// Method which make authentication of a user using her login and password.This method use "MemberShip" class for Asp.Net Authentication
        /// </summary>
        /// <param name="username">Name of user</param>
        /// <param name="password">Password of user</param>
        /// <returns>boolean</returns>
        public static bool Authenticate(string username, string password)
        {
            if (Membership.ValidateUser(username, password))
            {
                User.Username = username;
                User.Roles = Roles.GetRolesForUser(username);

                User.Principal = new GenericPrincipal(new GenericIdentity(username, Membership.Provider.Name), User.Roles);
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// Method which check if user is authorized to do a task..
        /// </summary>
        /// <param name="rule">Name of rule</param>
        /// <returns>boolean</returns>
        public static bool IsAuthorized(string rule)
        {
            return EnterpriseLibraryContainer.Current
                .GetInstance<IAuthorizationProvider>("Authorization Rule Provider")
                .Authorize(User.Principal, rule);
        }
    }

    /// <summary>
    /// Representation of User
    /// </summary>
    internal static class User
    {
        /// <summary>
        /// List of User's Roles
        /// </summary>
        public static string[] Roles { get; set; }

        /// <summary>
        /// Name of User
        /// </summary>
        public static string Username { get; set; }

        public static IPrincipal Principal { get; set; }
    }
}
